const mongoose = require('@/db/core')
const versionKey = { versionKey: false } // 去掉mongoose自动带 __v 的字段
const { Schema, model } = mongoose

// 院系
const SdeptSchema = new Schema({
  name: String,
  description: String
},versionKey)
// 院系课程
const SdeptCourseSchema = new Schema({
  name: String,
  cour_id: Array
})
// 班级
const ClassSchema = new Schema({
  name: String,
  sdept_id: String,
  description: String
},versionKey)
// 菜单
const MenuSchema = new Schema({
  name: {
    type: String,
    unique: true
  },
  en_name: String,
  description: String,
  children: {
    type: Array,
    default: []
  },
  is_enable: {
    type: Number,
    default: 0
  }
})
// 角色菜单
const MenuRoleSchema = new Schema({
  menu_id: Array,
  role_id: Number
})
// 角色
const RoleSchema = new Schema({
  name: String,
  description: String,
  level: Number
})
// 学生表
const StudentSchema = new Schema({
  stu_id: Number,       // 学生学号
  stu_name: String,     // 学生姓名
  stu_age: Number,      // 学生年龄
  stu_gander: String,   // 学生性别
  stu_address: String,   // 学生户籍
  sdept_name: String,   // 学院
  sdept_id: String,   // 学院
  class_name: String    // 班级
},versionKey)
// 教师表
const TeacherSchema = new Schema({
  tea_id: Number,     // 教师编号
  tea_name: String,   // 教师姓名
  tea_age: Number,    // 教师年龄
  tea_gander: String, // 教师性别
  tea_address: String // 教师户籍
})
// 课程表
const CourseSchema = new Schema({
  cour_id: Number,     // 课程编号
  cour_name: String,   // 课程姓名
  cour_time: Date      // 课程时间
})
// 课程对应教师表
const CourseTeacherSchema = new Schema({
  cour_id: Number,     // 课程编号
  tea_id: Number       // 教师编号
})
// 成绩表
const ScoreSchema = new Schema({
  cour_id: Number, // 课程编号
  stu_id: Number,  // 学生学号
  sco_score: Number // 分数
})
// 学生对应课程表
const StudentCourseSchema = new Schema({
  cour_id: Number, // 课程编号
  tea_id: Number, // 老师编号
  stu_id: Number  // 学生学号
},versionKey)
// stu_id字段递增
StudentSchema.pre('save', async function(next) {
  // const count= await model('student', StudentSchema).find().count();
  // this.stu_id = Number('2024' + (1000 + count + 1));
  // 找到最后一条 加一
  const count = await model('student', StudentSchema).findOne({},{},{sort: {_id: -1}}, (err,result)=>{
    return result
  })
  this.stu_id = Number(count.stu_id + 1);
  next()
});
module.exports = {
  modelStudent: model('student', StudentSchema),
  modelTeacher: model('teacher', TeacherSchema),
  modelCourse: model('course', CourseSchema),
  modelCourseTeacher: model('courseTeacherRelation', CourseTeacherSchema),
  modelScore: model('score', ScoreSchema),
  modelMenu: model('menu', MenuSchema),
  modelSdept: model('sdept', SdeptSchema),
  modelClass: model('class', ClassSchema),
  modelStudentCourse: model('studentCourseRelation', StudentCourseSchema),
  modelMenuRole: model('menuRoleRelation', MenuRoleSchema),
  modelRole: model('role', RoleSchema),
  modelSdeptCourse: model('sdeptCourseRelation', SdeptCourseSchema),
}
